package util;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class Loginfilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器开启");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
       // System.out.println("开始过滤");

        //防止用户在未登录的情况下访问资源
        String requestURI = request.getRequestURI();//获得请求地址
        System.out.println("requestURI="+requestURI);
        Object username = request.getSession().getAttribute("userName");

        if(requestURI.endsWith("sucess.jsp")&&username==null){
            System.out.println("无法访问，请先登录在");
            response.sendRedirect("index.jsp");
        }
        filterChain.doFilter(servletRequest,servletResponse);
        //System.out.println("过滤结束");
    }

    @Override
    public void destroy() {
        System.out.println("过滤器销毁");
    }
}
